package com.byit.controller;

import com.alibaba.fastjson.JSONObject;
import com.byit.builder.MapBuilder;
import com.byit.domain.AppCertificate;
import com.byit.enums.PromptInfo;
import com.byit.jwt.ann.JwtUser;
import com.byit.jwt.domain.JwtSession;
import com.byit.msg.MessageResult;
import com.byit.service.IAppCertificateService;
import com.byit.service.IAppNewsService;
import com.byit.utils.IdcardUtil;
import com.byit.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName AppCertificateController
 * @Description 证件管理
 * @Author lxp
 * @Date 2019-01-09 18:37
 **/
@RestController
@RequestMapping("/app/certificate")
public class AppCertificateController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IAppCertificateService appCertificateService;

    @Autowired
    private IAppNewsService appNewsService;

    /**
     * 新增或修改证件管理信息
     *
     * @param session
     * @return
     */
    @PostMapping("/add")
    public Object insertAnnouncement(@JwtUser JwtSession session,
                                     MultipartFile card1,
                                     MultipartFile card2,
                                     @RequestParam("cardNo") String cardNo,
                                     @RequestParam("type") int type,
                                     @RequestParam(value = "cardType" ,defaultValue="") String cardType,
                                     @RequestParam(value = "name" ,defaultValue="") String name,
                                     @RequestParam(value = "remark" ,defaultValue="") String remark
                                    ) {
        if (type == 1) {

            if (! IdcardUtil.validateCard(cardNo)) {
                return MessageResult.error(PromptInfo.ERROR_ID_CARD);
            }
        }
        AppCertificate appCertificate = new AppCertificate();
        appCertificate.setCardNo(cardNo);
        appCertificate.setName(name);
        appCertificate.setType(type);
        appCertificate.setCardType(cardType);
        appCertificate.setRemark(remark);
        Long userId = session.userId();
        if (userId == null) {
            return MessageResult.error(PromptInfo.NOT_LOGGED);
        }
        try {
            if (null == appCertificate) {
                return MessageResult.warpper(PromptInfo.ERROR_PARAM_NOT_NULL);
            }
            StringBuilder sb = new StringBuilder();
            if (card1 != null) {

                sb.append(appNewsService.getPictrePath(card1,
                        "appCertificate/" + appCertificate.getType()));
            }
            if (card2 != null) {
                sb.append(","+appNewsService.getPictrePath(card2,
                        "appCertificate/" + appCertificate.getType()));
            }
            appCertificate.setPicture(sb.toString());
            appCertificate.setCreateTime(new Date());
            appCertificate.setUpdateTime(new Date());
            // 加密用户密码
            appCertificate.setOperationId(userId);
            appCertificate.setUserId(userId);

            appCertificateService.insertOrUpdate(appCertificate);
            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e);
        }
    }


    /**
     * 查询证件
     *
     * @param session
     * @param appCertificate
     * @return
     */
    @GetMapping("/list")
    public Object list(@JwtUser JwtSession session, AppCertificate appCertificate) {
        Long userId = session.userId();
        if (userId == null) {
            return MessageResult.error(PromptInfo.NOT_LOGGED);
        }
        // Long userId = SessionHelper.getUserId(session);
        try {

            // 加密用户密码
            appCertificate.setOperationId(userId);

            Map<String, Object> params = MapBuilder.newMap(1).setParam("userId", userId)
                    //.setParam("type",appCertificate.getType())
                    .ok();

            List<JSONObject> appCertificateList = appCertificateService.selectListUserCertificates(params);
            return MessageResult.warpper(PromptInfo.SYS_SECCUSS, appCertificateList);
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e);
        }
    }

    /**
     * 修改证件管理信息
     *
     * @param session
     * @param card1          证件图片正面
     * @param card2          证件图片反面
     * @param appCertificate
     * @return
     */
    @PostMapping("/edit")
    public Object editAppCertificate(@JwtUser JwtSession session,
                                     MultipartFile card1,
                                     MultipartFile card2,
                                     AppCertificate appCertificate) {


        Long userId = session.userId();
        if (userId == null) {
            return MessageResult.error(PromptInfo.NOT_LOGGED);
        }
        try {
            if (null == appCertificate) {
                return MessageResult.warpper(PromptInfo.ERROR_PARAM_NOT_NULL);
            }
            Map<String, Object> params = MapBuilder.newMap(2).setParam("userId", userId)
                    .setParam("type", appCertificate.getType())
                    .ok();
            List<JSONObject> appCertificateList = appCertificateService.selectUserCertificateByType(params);
            String picture = appCertificateList.get(0).getString("picture");
            String[] splitUrls = picture.split(",");
            //分别替换正面和反面照片
            StringBuilder sb = new StringBuilder();
            if (splitUrls.length != 0) {
                if (splitUrls.length == 1) {

                    if (card1 != null) {

                        sb.append(appNewsService.getPictrePath(card1,
                                "appCertificate/" + appCertificate.getType()));

                    }
                    if (card2 != null) {
                        sb.append(","+appNewsService.getPictrePath(card1,
                                "appCertificate/" + appCertificate.getType()));

                    }
                }
                if (splitUrls.length == 2) {
                    if (card1 != null) {

                        splitUrls[0] = appNewsService.getPictrePath(card1,
                                "appCertificate/" + appCertificate.getType());
                        sb.append(splitUrls[0]);

                    }
                    if (card2 != null) {

                        splitUrls[1] = appNewsService.getPictrePath(card1,
                                "appCertificate/" + appCertificate.getType());
                        sb.append(","+splitUrls[1]);

                    }
                }
            }

            appCertificate.setPicture(sb.toString());
            //// 加密用户密码
            appCertificate.setOperationId(userId);
            //更新
            appCertificate.setId(appCertificateList.get(0).getLong("id"));
            appCertificateService.updateById(appCertificate);
            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e);
        }
    }

    /**
     * 证件解绑==>
     *
     * @param session
     * @return
     */
    @PostMapping("/del")
    public Object delAppNewsByIds(@JwtUser JwtSession session, @RequestParam("type") int type) {
        Long userId = session.userId();

        if (userId == null) {
            return MessageResult.error(PromptInfo.NOT_LOGGED);
        }
        if (StringUtil.isEmpty(type)) {
            return MessageResult.error();
        }
        Map<String, Object> params = MapBuilder.newMap(2).setParam("userId", userId)
                .setParam("type", type)
                .ok();
        List<JSONObject> appCertificateList = appCertificateService.selectUserCertificateByType(params);
        Long id = appCertificateList.get(0).getLong("id");
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        appCertificateService.delAppCertificateById(map);
        return MessageResult.success();
    }


}
